lst = [1, 2, 2, 2, 2, 2, 3, 3, 4, 4, 5]


def list_to_dict(lst):
    # 检查列表是否为空
    if not lst:
        raise ValueError("输入的列表不能为空")
    # 使用字典推导式创建字典，列表中的每个元素作为键，值为空格字符串
    return {item: ' ' for item in lst}


def get_test_name(file_path):
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()
            test_names = []
            found_testname = False
            for line in lines:
                if line.startswith('[Testname]'):
                    found_testname = True
                elif found_testname:
                    if len(line) >= 31:
                        test_names.append(line[:31].strip())
            return test_names
    except Exception as e:
        print(f"Error in get_test_name for file {file_path}: {e}")
        return []


def create_test_dict(file_path):
    test_dict = {}
    name_lst = get_test_name(file_path)
    name_dic = list_to_dict(name_lst)
    for itme in name_dic:
        test_name = itme
        test_dict[test_name] = {'states': None, 'Result': None, 'Min': None, 'Max': None}
    return test_dict



def fill_test_dict(file_path, test_dict):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        # 找到标题行的索引
        header_index = None
        name_lst = get_test_name(file_path)
        for i, line in enumerate(lines):
            if '[Testname]' in line:
                header_index = i
                break
        if header_index is None:
            return
        for line in lines[21:]:
            parts = line.split()
            name =''
            if len(line) >= 31:
                name = line[:31].strip()
            if len(parts) < 4:
                continue
            if 'passed' in parts:
                index = parts.index('passed')
            elif 'failed' in parts:
                index = parts.index('failed')
            if 'TD>30' in parts:
                _index = parts.index('TD>30')
                parts.pop(_index)
            if index != 0:
                state = parts[index]
                min_val = parts[index + 1]
                if 'DEC"' in parts:
                    max_val = parts[index + 5]
                    result = parts[index + 3]
                else:
                    max_val = parts[index + 3]
                    result = parts[index + 2]
            # fail_test_data.extend([state, min_val, result, max_val])
        # 填充字典的值
            if name in test_dict:
                test_dict[name]['states'] = state
                test_dict[name]['Result'] = result
                test_dict[name]['Min'] = min_val
                test_dict[name]['Max'] = max_val



from openpyxl import Workbook


def extract_data(data):
    result = {}
    # 提取外层字典的指定键值
    keys_to_extract = ['Serial number', 'Module State', 'Date_Time', 'Testplan_number']
    for key in keys_to_extract:
        result[key] = data.get(key)
    # 提取嵌套字典的数据
    nested_key = '001110010, Connector_module_ve'
    nested_dict = data.get(nested_key)
    if nested_dict:
        sub_keys = ['Max', 'Min', 'Result', 'states']
        for sub_key in sub_keys:
            result[f'{nested_key}_{sub_key}'] = nested_dict.get(sub_key)
    return result


def write_to_excel(data, file_path):
    # 创建一个新的工作簿
    wb = Workbook()
    # 获取活动工作表
    ws = wb.active

    # 写入表头
    headers = list(data.keys())
    ws.append(headers)

    # 写入数据行
    row = list(data.values())
    ws.append(row)

    # 保存工作簿
    wb.save(file_path)


# 示例数据
data = {
    'Serial number': 1234,
    'Module State': 'pass',
    'Date_Time': 123,
    'Testplan_number': 1234,
    '001110010, Connector_module_ve': {
        'Max': '"3.0"',
        'Min': '"3.0"',
        'Result': '"3.0"',
        'states': 'passed'
    }
}

# 提取数据
extracted_data = extract_data(data)

# 写入 Excel 文件
file_path = 'output.xlsx'
write_to_excel(extracted_data, file_path)
print(f"数据已成功写入 {file_path}")

# 示例用法
# file_path = r'D:\wangbo\ForPythonTes\forPythonTest\MFT reportSummary\239_M4REK_002_FT_AAA2143300001_12_20240318084728\RT-TEST_20_26_59_RT-TEST_CGQW501T_21433000012402230175_20240315_202807.txt'
# test_dict = create_test_dict(file_path)
# fill_test_dict(file_path, test_dict)
# import pprint
#
# pprint.pprint(test_dict)

# print(list_to_dict(lst))
